package porotos;

import java.util.List;

import javax.annotation.ManagedBean;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import entidades.Registro;

@ManagedBean
@RequestScoped
@Stateful
public class AdminRegistros {

	private EntityManager entityManager;
	
	AdminRegistros() {} // necesario para que este managed bean sea proxyable

	@Inject
	AdminRegistros(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	List<Registro> getRegistros() {
		List<Registro> registros = this.entityManager.createQuery("select r from Registros r",
				Registro.class).getResultList();
		if( registros == null || registros.isEmpty()) {
			registros.add(new Registro(123,"Abc"));
			registros.add(new Registro(456, "Def"));
		}
		return registros;
	}

	void agregarRegistro(Registro registro) throws EntityExistsException {
		this.entityManager.persist(registro);
	}

	void reemplazarRegistro(Registro nuevo, Registro viejo) {
		EntityTransaction transaction = this.entityManager.getTransaction();
		transaction.begin();
		try {
			this.entityManager.remove(viejo);
			this.entityManager.persist(nuevo);
			transaction.commit();
		} catch (Throwable t) {
			transaction.rollback();
		}
	}
}
